// 实际观察的元素
var actrulEle = null;

const scale = {
    width: "1",
    height: "1",
};

// * 设计稿尺寸（px）
const baseWidth = 1920;
const baseHeight = 1080;
const minWidth = 600; // 最小宽度
const minHeight = 600 * baseHeight / baseWidth; // 最小高度

// * 需保持的比例（默认1.77778）
const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5));

let flag = false; // 是否已经开始监听

/* 
 * @param { HTMLElement } watchEl 等待观察的外部元素
 * @param { HTMLElement } el 实际需要响应外部元素改变而改变大小的内部元素
 * @param { Boolean } 确认是否进行或者取消监听
*/
const useWatchElement = (watchEl, el, watchFlag = true) => {
    actrulEle = el;
    if (ob && !el && !watchFlag) {
        ob.unobserve(watchEl);
        return false;
    }
    ob.observe(watchEl);
    return {
        width: baseWidth,
        height: baseHeight,
        scale,
    }
};

const calcRate = () => {
    const appRef = actrulEle;
    if (!appRef) return;
    // 获取待监听屏幕的长宽
    let width = window.innerWidth;
    let height = window.innerHeight;
    // 当前宽高比
    let currentRate = parseFloat((width / height).toFixed(5));
    if (width != 0 && height != 0) {
        // 计算当前宽高比与基准宽高比的关系
        if (width < minWidth || height < minHeight) {
            // 宽度小于 600 的时候取消适配，大于等于 600 重新适配
            width = minWidth;
            height = minHeight;
            currentRate = parseFloat((width / height).toFixed(5));
        }
        if (currentRate > baseProportion) {
            // 表示比基准宽高更宽
            scale.width = ((height * baseProportion) / baseWidth).toFixed(5);
            scale.height = (height / baseHeight).toFixed(5);
            appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`;
        } else {
            // 表示比基准宽高更高
            scale.height = (width / baseProportion / baseHeight).toFixed(5);
            scale.width = (width / baseWidth).toFixed(5);
            appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`;
        }
        document.documentElement.style.setProperty("--bigscreen-bg-scale", scale.width);    // 全局改变样式
    } else {
        return false;
    }
};

let ids = null

const ob = new ResizeObserver((e) => {
    const target = e[0].target;
    if (target.offsetWidth != 0 && target.offsetHeight != 0) {
        if (ids) {
            window.cancelAnimationFrame(ids)
        }
        if (target.offsetWidth < minWidth || target.offsetHeight < minHeight) {
            // 宽度小于 600 的时候取消适配，大于等于 600 重新适配
            // 表示比基准宽高更宽
            scale.width = ((minHeight * baseProportion) / baseWidth).toFixed(5);
            scale.height = (minHeight / baseHeight).toFixed(5);
            actrulEle.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`;
            document.documentElement.style.setProperty("--bigscreen-bg-scale", scale.width);    // 全局改变样式
            window.cancelAnimationFrame(ids)
            ids = null
            return false;
        }
        if (flag) {
            debounce(() => {
                ids = window.requestAnimationFrame(() => calcRate(target))
            }, 500)();
        }
        if (!flag) {
            calcRate(target)
            flag = true
        }
    }
});

/**
 * 防抖函数
 * @param {T} fn
 * @param {number} delay
 * @return
 */
function debounce(fn, delay = 100) {
    let timer = null;
    return function (...args) {
        timer = setTimeout(
            () => {
                typeof fn === "function" && fn.apply(null, args);
                clearTimeout(timer);
            },
            delay > 16 ? delay : 100
        );
    };
}

export default useWatchElement;
